package com.app.micaihu.view.user.userinfo.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.base.BaseActivity;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.ad.NativeAd;
import com.app.micaihu.bean.game.GameContent;
import com.app.micaihu.bean.infor.GetTaskBean;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.bean.news.ShareBean;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.custom.components.downandupload.DownloadUtils;
import com.app.micaihu.utils.ImageLoadUtils;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.view.main.game.GameDownloadActivity;
import com.app.okhttplib.OkHttpUtil;
import com.app.okhttplib.annotation.DownloadStatus;
import com.app.okhttplib.bean.DownloadFileInfo;
import com.app.widget.CommonTitle;
import com.app.widget.LoadView;
import com.app.micaihu.custom.view.dialog.CustomDialog;
import com.app.micaihu.custom.view.web.CustomWebView;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.AppShareUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.view.main.MainActivity;
import com.app.micaihu.view.main.topic.PostSendActivity;
import com.app.micaihu.view.user.usertask.UserTaskActivity;
import com.app.utils.util.LogUtils;
import com.app.utils.util.ToastUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

/**
 * 公用的显示网页页面
 * Created by Guo on 2016/7/18.
 */
public class WebActivity extends BaseActivity {
    public final static String PARAMETER1 = "parameter1";//通用的参数1
    /**
     * title名
     */
    private String title;
    /**
     * 加载的url
     */
    private String url;
    private FrameLayout flContent;
    private CustomWebView webView;

    private ProgressBar webViewProgressBar;
    private boolean isShowPageFinish = true;// 是否展示页面加载完成

    private JavascriptInterface javascriptInterface;
    private CommonTitle commonTitle;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_web;
    }

    @Override
    public void getBundle(@NotNull Bundle bundle) {
        title = bundle.getString(Config.Extra.title);
        url = bundle.getString(Config.Extra.url);
    }

    @Override
    protected void setData() {
        initView();
        initWebView();
        LogUtils.e("gzq", "url->" + url + "    title_" + title);
        if (!TextUtils.isEmpty(url)) {
            String night = "0";
            if (url.contains("?")) {
                url += "&night=" + night;
            } else {
                url += "?night=" + night;
            }
            webView.loadUrl(url);
        } else {
            webView.loadUrl("about:blank");// 避免出现默认的错误界面
        }
    }

    @Override
    protected void addListeners() {
//        String isMain = getIntent().getStringExtra("isMain");
        commonTitle.setCommonTitleCallBackListener(new CommonTitle.CommonTitleCallBackListener() {
            @Override
            public void btnBackOnClick() {
//                if ("1".equals(isMain)) {
                    Log.e("JF", "addListeners: ===================================");
//                    startActivity(new Intent(WebActivity.this, MainActivity.class));
//                    finish();
//                } else {
                    if (webView != null && webView.canGoBack()) {
                        webView.goBack();
                    } else {
                        finish();
                    }
//                }
            }

            @Override
            public void btnConfirmOnClick() {

            }
        });
    }

    /**
     * 初始化页面
     */
    private void initView() {
        commonTitle = getCommonTitle();
        flContent = findViewById(R.id.flContent);
        webViewProgressBar = findViewById(R.id.webViewProgressBar);
        webView = new CustomWebView(getApplicationContext());
        flContent.addView(webView);
        Log.e("JF", "addListeners: ===================================");
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = webView.getSettings();
//        settings.setBlockNetworkImage(true);// 延迟图片加载
        settings.setSavePassword(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        // 启动缓存
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        // 设置缓存模式
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.setBackgroundColor(Color.argb(0, 0, 0, 0));
        //手动获取焦点
        webView.setFocusable(true);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient());
        webView.requestFocus();
        settings.setLoadsImagesAutomatically(true);
        javascriptInterface = new JavascriptInterface(WebActivity.this);
        webView.addJavascriptInterface(javascriptInterface, "android");
    }

    /**
     * 创建静态内部类
     */
    private static class MyHandler extends Handler {
        //持有弱引用HandlerActivity,GC回收时会被回收掉.
        private final WeakReference<WebActivity> mActivity;

        public MyHandler(WebActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            WebActivity activity = mActivity.get();
            super.handleMessage(msg);
            if (activity != null) {
                //执行业务逻辑
                switch (msg.what) {
                    case 0://展示错误界面
                        ToastUtils.makeText(activity.getResources().getString(R.string.neterror));
                        break;
                    case 1://展示分享界面
                        CustomDialog.getInstance().showShareDialog(activity, activity.onClickInviteListener);
                        break;
                    case 3://修改标题
                        String title = (String) msg.obj;
                        activity.setTitle(title);
                        break;
                    case 4://返回到webview 首页
                        if (activity.webView != null) {
                            while (activity.webView.canGoBack()) {
                                activity.webView.goBack();
                            }
                        }
                    case 5://跳转军团
                        ActivityUtils.finishToActivity(MainActivity.class, false);
                        LiveEventBus.get(Config.EventBus.goArmy).post(true);
                        break;
                }
            }
        }
    }


    /**
     * js 可调用的方法
     */
    @SuppressLint("JavascriptInterface")
    public class JavascriptInterface {

        private Activity activity;
        private String json;
        private MyHandler handler = new MyHandler(WebActivity.this);

        public JavascriptInterface(Activity activity) {
            this.activity = activity;
        }

        @android.webkit.JavascriptInterface
        public void getData(String json) {
            this.json = json;
            if (TextUtils.isEmpty(json)) {
                Message msg = Message.obtain();
                msg.what = 0;
                handler.sendMessage(msg);
            } else {
                Message msg = Message.obtain();
                msg.what = 1;
                handler.sendMessage(msg);
            }
        }


        //返回json字符串
        public String getJson() {
            if (TextUtils.isEmpty(json)) {
                return "";
            } else {
                return json;
            }
        }

        /**
         * 显示title
         *
         * @param html
         */
        @android.webkit.JavascriptInterface
        public void showSource(String html) {
            Message msg = Message.obtain();
            if (TextUtils.isEmpty(html)) {
                html = " ";
            }
            msg.what = 3;
            msg.obj = html;
            handler.sendMessage(msg);
        }


        @android.webkit.JavascriptInterface
        public void jumpFightCenter(String json) {
            onBackPressed();
            startActivity(new Intent(WebActivity.this, UserTaskActivity.class));

        }


        @android.webkit.JavascriptInterface
        public void bashOrder(String json) {
            this.json = json;
            Gson gson = new Gson();
            try {
                BashOrder bashOrder = gson.fromJson(json, BashOrder.class);
                if (bashOrder != null) {
                    Intent intent = new Intent(WebActivity.this, PostSendActivity.class);
                    intent.putExtra(PARAMETER1, true);
                    startActivity(intent);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @android.webkit.JavascriptInterface
        public void downloadGame(String gameJson) {
            try {
                if (StringUtils.isEmpty(gameJson)) return;
                com.blankj.utilcode.util.LogUtils.e(gameJson);
                GameContent gameContent = GsonUtils.fromJson(gameJson, GameContent.class);
                if (gameContent != null) {
                    boolean appInstalled = AppUtils.isAppInstalled(gameContent.getPackageName());
                    if (appInstalled) {
                        com.app.okhttplib.util.AppUtils.startUpApp(getThisContext(), gameContent.getIPackageName());
                    } else {
                        File unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, gameContent.getIPath() + ".apk");
                        if (unInstallFile.exists() && unInstallFile.isFile()) {//安装游戏
                            com.app.okhttplib.util.AppUtils.installAPP(getThisContext(), unInstallFile);
                        } else {
                            DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(gameContent.getIUrl()));
                            com.blankj.utilcode.util.LogUtils.e(getClassTag(), "downloadFileInfo->" + downloadFileInfo);
                            if (downloadFileInfo == null) {
                                ToastUtils.makeText("开始下载");
                                DownloadUtils.getSingleton().down(gameContent.getIUrl(), gameContent.getIPath(), gameContent);
                                GameDownloadActivity.insertGame(gameContent.getIGameId(), gameContent.getITitle(), gameContent.getIUrl(), gameContent.getIAppIcon(),
                                        gameContent.getIGameSummary(), gameContent.getIPackageName(), gameContent.getIPath(), gameContent.getISize());
                            } else {
                                String downloadStatus = downloadFileInfo.getDownloadStatus();
                                if (!DownloadStatus.DOWNLOADING.equals(downloadStatus)) {
                                    ToastUtils.makeText("开始下载");
                                    DownloadUtils.getSingleton().down(gameContent.getIUrl(), gameContent.getIPath(), gameContent);
                                    GameDownloadActivity.insertGame(gameContent.getIGameId(), gameContent.getITitle(), gameContent.getIUrl(), gameContent.getIAppIcon(),
                                            gameContent.getIGameSummary(), gameContent.getIPackageName(), gameContent.getIPath(), gameContent.getISize());
                                }
                                com.blankj.utilcode.util.LogUtils.e(getClassTag(), "getDownloadStatus->" + downloadStatus);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        class BashOrder {
            public String topicId;
            public String topicTitle;

            public String getTopicId() {
                return topicId;
            }

            public String getTopicTitle() {
                return topicTitle;
            }

        }


        /**
         * 返回首页
         */
        @android.webkit.JavascriptInterface
        public void exchangeIndex(String json) {
            Message msg = Message.obtain();
            msg.what = 4;
            handler.sendMessage(msg);
        }

        /**
         * 跳转军团
         */
        @android.webkit.JavascriptInterface
        public void JumpLegion() {
            Message msg = Message.obtain();
            msg.what = 5;
            handler.sendMessage(msg);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //设置友盟回调
        try {
            if (data != null) {
                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 分享弹窗的点击监听
     */
    private CustomDialog.OnClickInviteListener onClickInviteListener = new CustomDialog.OnClickInviteListener() {
        @Override
        public void qqInvite() {
            ShareBean shareBean = returnShareBean();
            AppShareUtils.getInstance().setQQShareContent(WebActivity.this, shareBean, umInviteListener);
        }

        @Override
        public void wxInvite() {
            ShareBean shareBean = returnShareBean();
            AppShareUtils.getInstance().setWXShareContent(WebActivity.this, shareBean, umInviteListener);
        }

        @Override
        public void wxFriendsInvite() {
            ShareBean shareBean = returnShareBean();
            AppShareUtils.getInstance().setWXCShareContent(WebActivity.this, shareBean, umInviteListener);
        }
    };


    /**
     * 邀请后的回调
     */
    public UMShareListener umInviteListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtils.makeText(R.drawable.handle_success, "分享成功");

            StatisticInvite(platform);
            StatService.onEvent(getApplicationContext(), "010", "邀请好友成功", 1);//统计事件的点击次数

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.makeText(R.drawable.handle_fail, "分享失败");
            StatService.onEvent(getApplicationContext(), "011", "邀请好友失败", 1);//统计事件的点击次数
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtils.makeText("分享取消");
        }

    };

    /**
     * 统计邀请次数
     *
     * @param platform 平台号
     */
    private void StatisticInvite(SHARE_MEDIA platform) {
        if (platform == null) {
            ToastUtils.makeText(R.drawable.handle_fail, "分享失败");
            return;
        }
        ParamMap param = new ParamMap();
        String type = "0";
        if (SHARE_MEDIA.SINA.equals(platform.toSnsPlatform().mPlatform)) {
            type = "1";
        } else if (SHARE_MEDIA.WEIXIN.equals(platform.toSnsPlatform().mPlatform)) {
            type = "2";
        } else if (SHARE_MEDIA.WEIXIN_CIRCLE.equals(platform.toSnsPlatform().mPlatform)) {
            type = "3";
        } else if (SHARE_MEDIA.QQ.equals(platform.toSnsPlatform().mPlatform)) {
            type = "4";
        } else if (SHARE_MEDIA.QZONE.equals(platform.toSnsPlatform().mPlatform)) {
            type = "5";
        } else {
            type = "0";
        }
        param.putEncode("channelType", type);
        if (UserInforManager.getInstance() != null) {
            param.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
        } else {
            param.putEncode("uid", "");
        }
        HttpUtils.ParmsMapMD5(param);

        HttpUtils.addPostRequest(URIContant.INVITE_COUNT, new TypeToken<DataBean<GetTaskBean>>() {
        }.getType(), "web", param, httpListener);
    }

    private HttpListener httpListener = new HttpListener<DataBean<GetTaskBean>>() {
        @Override
        public void onError(VolleyError error) {

        }

        @Override
        public void onSuccess(DataBean<GetTaskBean> response) {
            if (response.noError() && response.getData() != null
                    && response.getData().getIsGetTask("邀请好友")) {
                //刷新任务
                UserInforManager.getInstance().getUserTask(getApplicationContext(), false);

            }
        }
    };


    /**
     * 返回一个shareBean
     *
     * @return
     */
    private ShareBean returnShareBean() {
        ShareBean shareBean = null;
        if (javascriptInterface == null) {
            javascriptInterface = new JavascriptInterface(WebActivity.this);
        }
        String json = javascriptInterface.getJson();
        Gson gson = new Gson();
        try {
            shareBean = gson.fromJson(json, ShareBean.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return shareBean;
    }


    // 监听
    private class MyWebViewClient extends WebViewClient {


        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) {
            sslErrorHandler.proceed();
        }


        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            if (TextUtils.isEmpty(url) || url.length() < 5) {
                return false;
            }
            //判断是否为http协议，如果是自定义协议则交给系统
            String httpStr = "";
            try {
                httpStr = url.substring(0, 4);
            } catch (Exception e1) {
                e1.printStackTrace();
                return false;
            }
            if (!TextUtils.isEmpty(httpStr) && !httpStr.equals("http")
                    && !httpStr.equals("https") && !httpStr.equals("abou")) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            } else if (httpStr.equals("abou")) {
                return true;
            } else if (url.contains("wx.tenpay.com")) {
                Uri uri = Uri.parse(url);
                String Referer = uri.getQueryParameter("Referer");
                if (!StringUtils.isEmpty(Referer)) {
                    Map<String, String> headers = new HashMap<>();
                    headers.put("Referer", Referer);//第三方支付平台请求头 一般是对方固定
                    view.loadUrl(url, headers);
                } else {
                    view.loadUrl(url);
                }
                return true;
            } else {
                if (view != null) {
                    view.loadUrl(url);
                }
                return true;
            }
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
//            view.getSettings().setBlockNetworkImage(false);// 取消延迟加载

            if (isShowPageFinish) {
                isShowPageFinish = false;
                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }
                String title = view.getTitle();
                if (TextUtils.isEmpty(title)) {
                    title = " ";
                }
                view.loadUrl("javascript:window.android.showSource(document.getElementsByTagName('title')[0].innerHTML);");
            }

        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            if (url != null && url.equals(failingUrl)) {
                isShowPageFinish = false;
            }
            super.onReceivedError(view, errorCode, description, failingUrl);
        }


    }

    private class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (commonTitle != null && !StringUtils.isEmpty(title)) {
                commonTitle.setTitle(title);
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                if (webViewProgressBar != null) {
                    webViewProgressBar.setVisibility(View.GONE);
                }
            } else {
                if (webViewProgressBar != null) {
                    webViewProgressBar.setVisibility(View.VISIBLE);
                    webViewProgressBar.setProgress(newProgress);
                }
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event == null)
            return true;// 防止nullException
        if (keyCode == KeyEvent.KEYCODE_BACK && webView != null && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.destroy();
        }
        if (!ActivityUtils.isActivityExistsInStack(MainActivity.class)) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }
}
